package com.imooc.security.filter;

import com.imooc.security.entity.TokenInfo;
import com.imooc.security.log.AuditLog;
import com.imooc.security.log.AuditLogRepository;
import com.imooc.security.log.AuditLogService;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @ClassName AuditLogFilter
 * @Description TODO
 * @Author wushaopei
 * @Date 2021/5/3 19:23
 * @Version 1.0
 */
@Component
@Slf4j
public class AuditLogFilter extends ZuulFilter {

    @Autowired
    private AuditLogRepository auditLogRepository;

    @Autowired
    private AuditLogService auditLogService;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 2;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        log.info(" audit log insert ....");

        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();

        AuditLog log = new AuditLog();
        log.setCreateTime(new Date());
        log.setPath(request.getRequestURI());
        log.setMethod(request.getMethod());
        TokenInfo info = (TokenInfo) request.getAttribute("tokenInfo");
        if(info != null){
            log.setUsername(info.getUser_name());
        }
        auditLogRepository.save(log);
//        auditLogService.save(log);
        request.setAttribute("auditLogId",log.getId());
        return null;
    }
}
